<?php

namespace App\Http\Controllers\NonPublicVersion;

use App\Http\Controllers\Common;
use App\Http\Controllers\Data;
use App\Http\Controllers\ErrorCode;
use App\Http\Controllers\SuccessCode;
use App\Http\Requests\ChannelRequest;
use App\Model\ChannelLevel;
use App\Model\Cooperate;
use App\Model\GamePackage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Channel as Model;
use PhpParser\Node\Expr\BinaryOp\Mod;

class Channel extends Controller
{
    use Common;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $params = [];
        $name = $request->input('name','');
        $pid = $request->input('pid','');
        $oneChannel = $request->input('one_channel','');
        $twoChannel = $request->input('two_channel','');
        $cooperate = $request->input('cooperate','');
        $query = [
            'name' => $name,
            'pid' => $pid,
            'one_channel' => $oneChannel,
            'two_channel' => $twoChannel,
            'cooperate' => $cooperate,
        ];
        if ($name){
            $params['name']['key'] = 'name';
            $params['name']['condition'] = 'like';
            $params['name']['value'] = "%{$name}%";
        }

        if ($pid){
            $params['pid']['key'] = 'pid';
            $params['pid']['condition'] = '=';
            $params['pid']['value'] = $pid;
        }

        if ($oneChannel){
            $channelIds = ChannelLevel::where('name','like',"%{$oneChannel}%")->get()->unique('id')->pluck('id')->toArray();
            $params['one_channel']['key'] = 'one_channel';
            $params['one_channel']['condition'] = 'in';
            $params['one_channel']['value'] = $channelIds;
        }

        if ($twoChannel){
            $channelIds = ChannelLevel::where('name','like',"%{$twoChannel}%")->get()->unique('id')->pluck('id')->toArray();
            $params['two_channel']['key'] = 'two_channel';
            $params['two_channel']['condition'] = 'in';
            $params['two_channel']['value'] = $channelIds;
        }

        if ($cooperate){
            $params['cooperate_type_id']['key'] = 'cooperate_type_id';
            $params['cooperate_type_id']['condition'] = '=';
            $params['cooperate_type_id']['value'] = $cooperate;
        }

        $pageSize = $request->get('paginate',config('web.page.num'));
        $pageSize = $pageSize == 0 ? config('web.page.num') : $pageSize;

        if (!empty($params)){
            $lists = new Model();
            foreach ($params as $param) {
                    $lists = $param['condition'] == 'in' ?
                        $lists->whereIn($param['key'],$param['value']) :
                        $lists->where($param['key'],$param['condition'],$param['value']);
            }
            $lists = $lists->paginate($pageSize);
        } else{
            $lists = Model::where('pid','!=',0)->orderBy('id','DESC')->paginate($pageSize);
        }

        $lists->totalPage = ceil($lists->total() / $pageSize);
        $lists->url = url('/nonPublicVersion/channel');
        foreach ($lists as $key => $list) {
            $channel = ChannelLevel::where('id',$list->one_channel)->first();
            $twoChannel = ChannelLevel::where('id',$list->two_channel)->first();
            if ($list->cooperate_type_id){
                $cooperate = Cooperate::where('id',$list->cooperate_type_id)->first();
                $lists[$key]->cooperate = $cooperate->name;
            } else{
                $lists[$key]->cooperate = '';
            }
            $father = Model::where('id',$list->pid)->first();

            $lists[$key]->one_channel_name = $channel ? $channel->name : '-';
            $lists[$key]->two_channel_name = $twoChannel ? $twoChannel->name : '-';
            $lists[$key]->father = $father ? $father->name : '';
        }

        $topChannel = Model::where('pid',0)->get();
        $cooperate = Cooperate::all();

        return view('nonPublicVersion.channel.channel',[
            'lists' => $lists,
            'topChannel' => $topChannel,
            'cooperates' => $cooperate,
            'pageSize' => $pageSize,
            'query' => $query
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $topChannel = Model::where('pid',0)->get();
        $cooperate = Cooperate::all();
        $oneChannel = ChannelLevel::where('pid',0)->get();
        return view('nonPublicVersion.channel.add',[
            'topChannel' => $topChannel,
            'cooperates' => $cooperate,
            'oneChannel' => $oneChannel
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ChannelRequest $request)
    {
        $isOneChannel = $request->input('is_one_channel',null);
        $isTwoChannel = $request->input('is_two_channel',null);
        $name = $request->input('name',null);
        $pid = $request->input('pid',null);
        $oneChannel = $request->input('one_channel',null);
        $twoChannel = $request->input('two_channel',null);
        $cooperateTypeId = $request->input('cooperate_type_id',null);

        if ($isOneChannel){
            $model = new ChannelLevel();
            $model->name = $name;

            $find = ChannelLevel::where('name',$name)->where('pid',0)->first();

            if ($find){
                return $this->getView([],ErrorCode::CHANNEL_EXIST);
            }

            if ($model->save()){
                $channel = ChannelLevel::where('pid',0)->get();
                return view('nonPublicVersion/channel/oneChannel',[
                    'channels' => $channel
                ]);
            } else {
                return $this->getView([],SuccessCode::ADD_SUCCESS);
            }
        } elseif ($isTwoChannel){
            if (!$pid){
                return $this->getView([],ErrorCode::FATHER_CHANNEL_ERROR);
            }
            $model = new ChannelLevel();
            $model->name = $name;
            $model->pid = $pid;

            $find = ChannelLevel::where('name',$name)->where('pid',$pid)->first();

            if ($find){
                return $this->getView([],ErrorCode::CHANNEL_TOW_EXIST);
            }

            if ($model->save()){
                $channel = ChannelLevel::where('pid',$pid)->get();
                return view('nonPublicVersion.channel.oneChannel',[
                    'channels' => $channel
                ]);
            } else {
                return $this->getView([],ErrorCode::ADD_ERROR);
            }

        } else {

            $find = Model::where('id',$pid)->first();

            if (is_null($find)){
                return $this->getView([],ErrorCode::FATHER_CHANNEL_EMPTY);
            }

            $prefix = $find->name == '测试' ? 'FGBCS_' : 'FGB_';

            $id = Model::insertGetId([
                'name' => $name,
                'pid' => $pid,
                'cooperate_type_id' => $cooperateTypeId,
                'one_channel' => $oneChannel,
                'two_channel' => $twoChannel
            ]);


            $uuid = '';
            $uuid .= $prefix . $pid . '_' . $oneChannel . '_';

            if ($twoChannel){
                $uuid .= $twoChannel . '_' . $id;
            } else {
                $uuid .= $id;
            }

            Model::where('id',$id)->update([
                'unique_id' =>$uuid
            ]);

            if ($id){
                return $this->getView([],SuccessCode::ADD_SUCCESS);
            } else {
                return $this->getView([],ErrorCode::ADD_ERROR);
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Model::find($id);
        $topChannel = Model::where('pid',0)->get();
        $cooperate = Cooperate::all();
        $oneChannel = ChannelLevel::where('pid',0)->get();
        $currentOneChannel = ChannelLevel::where('id',$data->one_channel)->first();
        $currentTwoChannel = ChannelLevel::where('pid',$currentOneChannel ? $currentOneChannel->id : '')->get();

        return view('nonPublicVersion.channel.edit',[
            'oldData' => $data,
            'topChannel' => $topChannel,
            'cooperates' => $cooperate,
            'oneChannel' => $oneChannel,
            'currentTwoChannel' => $currentTwoChannel
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ChannelRequest $request, $id)
    {
        $name = $request->input('name','');
        $pid = $request->input('pid','');
        $cooperateTypeId = $request->input('cooperate_type_id','');
        $oneChannel = $request->input('one_channel','');
        $twoChannel = $request->input('two_channel','');

        $model = new Model();

        $find = Model::where('id',$pid)->first();

        if (is_null($find)){
            return $this->getView([],ErrorCode::FATHER_CHANNEL_EMPTY);
        }

        $prefix = $find->name == '测试' ? 'CS_' : 'FGB_';

        $uuid = '';
        $uuid .= $prefix . $pid . '_' . $oneChannel . '_';

        if ($twoChannel){
            $uuid .= $twoChannel . '_' . $id;
        } else {
            $uuid .= $id;
        }

        $model->where('id',$id)->update([
            'name' => $name,
            'pid' => $pid,
            'cooperate_type_id' => $cooperateTypeId,
            'one_channel' => $oneChannel,
            'two_channel' => $twoChannel,
            //'unique_id' => $uuid,
        ]);

        return $this->getView([],SuccessCode::EDIT_SUCCESS);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids = request()->get('ids','');

        if ($ids){
            $ids = explode(',',$ids);
            $errors = '';
            foreach ($ids as $id) {
                if ($errors){
                    continue;
                }
                $find = Model::find($id);
                if ($find){
                    if (GamePackage::where('channel_id',$id)->first()){
                        $errors = sprintf(ErrorCode::DELETE_ERROR_FOR_CHANNEL,$find->name);
                        continue;
                    }
                    if (Model::find($id)->delete()){
                        $errors = '';
                    }
                }
            }
            return $this->getView([],$errors ? $errors : SuccessCode::DEL_SUCCESS);
        } else {
            $find = Model::find($id);
            if ($find){
                if (GamePackage::where('channel_id',$id)->first()){
                    return $this->getView([],sprintf(ErrorCode::DELETE_ERROR_FOR_CHANNEL,$find->name));
                }
                if (Model::find($id) && Model::find($id)->delete()){
                    return $this->getView([],SuccessCode::DEL_SUCCESS);
                } else {
                    return $this->getView([],ErrorCode::DEL_ERROR);
                }
            }
        }

        return $this->getView([],ErrorCode::GAME_CONF_EXIST);
    }

    //获取该分类下的数据
    public function child(Request $request)
    {
        $pid = $request->input('pid','');
        $channel = ChannelLevel::where('pid',$pid)->get();
        $channel = $channel ? $channel->toArray() : $channel;
        return view('nonPublicVersion.channel.child',[
            'channels' => $channel
        ]);
    }

    //合作方式
    public function cooperate(Request $request)
    {
        $name = $request->input('name','');

        $find = Cooperate::where('name',$name)->first();

        if ($find){
            return $this->getView([],ErrorCode::COOPERATE_NAME_EXIST);
        }

        if (!$name){
            return $this->getView([],ErrorCode::COOPERATE_NAME_EMPTY);
        }
        $model = new Cooperate();
        $model->name = $name;
        if ($model->save()){
            $channel = Cooperate::all();
            return view('nonPublicVersion.channel.oneChannel',[
                'channels' => $channel
            ]);
        }
    }
}
